package com.goldgov.code.template.point.impl;

import com.goldgov.code.meta.Constraint;
import com.goldgov.code.meta.FieldInfo;
import com.goldgov.code.meta.ModuleInfo;
import com.goldgov.code.template.point.CodePoint;
import com.goldgov.code.utils.PackageUtils;
import com.goldgov.code.utils.StringUtils;

public class MyBatisResultMapAssociationCodePoint extends CodePoint{

	private final ModuleInfo relationModule;
	private final String relationName;
	private final String packageName;
	private boolean reference;

	public MyBatisResultMapAssociationCodePoint(String packageName,String relationName,ModuleInfo relationModule) {
		super("XML:MYBATIS:RESULT_MAP:ASSOCIATION");
		this.packageName = packageName;
		this.relationName = relationName;
		this.relationModule = relationModule;
	}

	@Override
	public String getCodes() {
		if(reference) {
			String packagePath = PackageUtils.joinPackageName(packageName, "dao", relationModule.getName() + "Dao",StringUtils.lowerFirstChar(relationModule.getName()));
			return "        <association property=\"" + relationName+ "\" resultMap=\"" + packagePath + "\">\r\n";
		}
		
		StringBuilder sb = new StringBuilder("        <association property=\"" + relationName+ "\">\r\n");
		FieldInfo[] fields = relationModule.getFields();
		for (FieldInfo fieldInfo : fields) {
			Constraint constraint = fieldInfo.getConstraint();
			if(constraint != null && constraint.isPrimaryKey()) {
				sb.append(String.format("            <id column=\"%s\" property=\"%s\"/>\r\n", fieldInfo.getName(),fieldInfo.getField()));
			}else {
				sb.append(String.format("            <result column=\"%s\" property=\"%s\"/>\r\n",  fieldInfo.getName(),fieldInfo.getField()));
			}
		}
		sb.append("        </association>\r\n");
		return sb.toString();
	}

	public boolean isReference() {
		return reference;
	}

	public void setReference(boolean reference) {
		this.reference = reference;
	}

}
